package cn.mw.cmdb.listener;

import cn.mw.cmdb.param.ContextAddListener;
import cn.mw.cmdb.param.ContextDeleteListener;
import cn.mw.cmdb.param.ContextEditorListener;
import cn.mw.cmdb.param.ContextListener;
import com.alibaba.nacos.common.utils.CollectionUtils;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.concurrent.Semaphore;
@Slf4j
public class InstanceListenersManager {
    /**
     * 并非控制工具
     */
    private Semaphore semaphore = new Semaphore(1);

    private List<InstanceChangeEventLister> instanceChangeEventListers = new ArrayList<>();

    /**
     * 添加监听者
     *
     * @throws Exception
     */
    public void addListerList(List<InstanceChangeEventLister> list) throws Exception {
        this.instanceChangeEventListers = list;
    }

    /**
     * 通知所有监听者
     *
     * @throws Exception
     */
    public Object notifyLister(ContextListener contextListener) throws Exception {
        Object obj = new Object();
        semaphore.acquire(1);
        if (CollectionUtils.isNotEmpty(instanceChangeEventListers)) {
            instanceChangeEventListers.sort(Comparator.comparing(s -> s.getSortLevel(), Comparator.nullsLast(Comparator.naturalOrder())));
            for (InstanceChangeEventLister instanceChangeEventLister : instanceChangeEventListers) {
                //新增
                if (contextListener instanceof ContextAddListener) {
                    log.info("addReceive");
                    instanceChangeEventLister.addReceive((ContextAddListener) contextListener);
                }
                //修改
                if (contextListener instanceof ContextEditorListener) {
                    log.info("editorReceive"+contextListener);
                    obj = instanceChangeEventLister.editorReceive((ContextEditorListener) contextListener);
                }
                //删除
                if (contextListener instanceof ContextDeleteListener) {
                    log.info("deleteReceive");
                    instanceChangeEventLister.deleteReceive((ContextDeleteListener) contextListener);
                }
            }
        }
        semaphore.release(1);
        return obj;
    }

}
